﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Windows.Forms;
using EnvDTE;
using EnvDTE80;
using EnvDTE90;
using System.Runtime.InteropServices;

namespace DatabaseGroup.SSIS.SourceAdapters.Setup
{
    [RunInstaller(true)]
    public partial class VisualStudioToolbox : Installer
    {
        public VisualStudioToolbox()
        {
            InitializeComponent();
        }

        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            try
            {
                RemoveFromToolbox();
            }
            catch (Exception ex)
            {
                if (MessageBox.Show("Failed to remove component from Visual Studio - ignore and continue?",
                    "Toolbox error", MessageBoxButtons.YesNo) == DialogResult.No)
                    throw ex;
            }
        }

        private bool RemoveFromToolbox()
        {
            Type dteReference;
            EnvDTE.ToolBox toolBox;

            dteReference = Type.GetTypeFromProgID("VisualStudio.DTE.8.0");
            if (dteReference != null)
            {
                EnvDTE80.DTE2 dte = (EnvDTE80.DTE2)Activator.CreateInstance(dteReference);
                toolBox = (EnvDTE.ToolBox)dte.Windows.Item("{B1E99781-AB81-11D0-B683-00AA00A3EE26}").Object;

                foreach (EnvDTE80.ToolBoxTab2 toolBoxTab in toolBox.ToolBoxTabs)
                {
                    if (toolBoxTab.Name.ToLower() == "data flow sources")
                    {
                        toolBoxTab.Activate();

                        foreach (EnvDTE80.ToolBoxItem2 toolBoxItem in toolBoxTab.ToolBoxItems)
                        {
                            if (toolBoxItem.Name == "DFS 2005")
                            {
                                toolBoxItem.Delete();
                                return true;
                            }
                        }
                    }
                }

                dte.Quit();
                Marshal.ReleaseComObject(dte);
                return false;
            }
            else
            {
                return false;
            }
        }
    }
}
